package com.glela.platform.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.mapper.UserPayInfoMapper;
import com.glela.platform.model.User;
import com.glela.platform.model.UserPayInfo;
import com.glela.platform.service.UserPayInfoService;

@Service("userPayInfoService")
public class UserPayInfoServiceImpl implements UserPayInfoService {
	//	private static Logger logger = LoggerFactory.getLogger(UserPayInfoServiceImpl.class);

	@Autowired
	private UserPayInfoMapper	userPayInfoMapper;
	@Autowired
	private UserMapper			userMapper;
	@Autowired
	protected RedisUtil			redisUtil;

	@Override
	public boolean existsPwd(Long userId) {
		boolean existsPwd = false;
		if (userId == null || userId < 1) {
			return existsPwd;
		}

		String userIdStr = userId.toString();
		if (StringUtils.equals("1", redisUtil.hget(RedisKeys.USER_PAY_HAS_PWD, userIdStr))) {
			existsPwd = true;
		} else {
			UserPayInfo queryByUserId = queryByUserId(userId);
			if (queryByUserId != null) {
				redisUtil.hmset(RedisKeys.USER_PAY_HAS_PWD, userIdStr, "1");
				existsPwd = true;
			}
			queryByUserId = null;
		}
		userIdStr = null;
		return existsPwd;
	}

	@Override
	public UserPayInfo queryByUserId(Long userId) {
		return userPayInfoMapper.queryByUserId(userId);
	}

	@Override
	public int resetPayPassword(String userId, String password) {
		return userPayInfoMapper.updatePassword(userId, password);
	}

	@Override
	public UserPayInfo queryUserPayInfoByUserId(String userId) {
		List<UserPayInfo> list = userPayInfoMapper.queryOneByUserId(userId);
		if (!list.isEmpty()) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public int insetNewOne(UserPayInfo userPayInfo) {
		return userPayInfoMapper.insertSelective(userPayInfo);
	}

	@Override
	public int updatePayPasswordById(Long userId, String payPwd, String newPayPwd) {
		int i;
		String id = userId + "";
		User user = userMapper.selectByPrimaryKey(userId);
		UserPayInfo payInfoList = userPayInfoMapper.queryByUserId(userId);
		//如果旧密码和数据库 不一致 将标记改为100
		if (payInfoList != null) {
			if (!payPwd.equals(payInfoList.getPwd())) {
				i = 100;
				return i;
			}
		}
		if (user == null) {
			i = 300;
			return i;
		}
		//支付密码 和 登录密码一致
		if (user != null) {
			if (newPayPwd.equals(user.getPassword())) {
				i = 200;
				return i;
			}
		}
		//修改密码
		i = userPayInfoMapper.updatePassword(id, newPayPwd);
		return i;
	}

}
